<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox, ElForm, ElIcon } from 'element-plus';
import { Plus, Search, Refresh } from '@element-plus/icons-vue';
import CommonLayout from '../components/CommonLayout.vue';
import materialApi from '../api/material.js';

// 搜索物料的辅助函数
const searchMaterialsApi = async (params) => {
  // 优先使用search方法，如果没有则使用getAll
  if (materialApi.search) {
    return materialApi.search(params);
  } else {
    return materialApi.getAll(params);
  }
};
import materialCategoryApi from '../api/materialCategory.js';

// 重置搜索表单
const resetSearch = () => {
  searchForm.name = '';
  searchForm.categoryPath = [];
  currentPage.value = 1;
  getMaterialList();
};


// 响应式数据
const materialList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchForm = reactive({
  name: '',
  categoryPath: [] // 使用数组存储级联选择的路径 [firstLevelId, secondLevelId]
});
const dialogVisible = ref(false);
const dialogTitle = ref('新增物料');
const formRef = ref(null); // 表单引用
const formData = reactive({
  id: 0,
  materialCode: '',
  name: '',
  specification: '',
  categoryPath: [], // 使用数组存储级联选择的路径 [firstLevelId, secondLevelId]
  description: '',
  status: 1
});
const rules = reactive({
  name: [
    { required: true, message: '请输入物料名称', trigger: 'blur' }
  ],
  materialCode: [
    { required: true, message: '请输入物料编码', trigger: 'blur' }
  ],
  specification: [
    { required: true, message: '请输入规格型号', trigger: 'blur' }
  ],
  categoryPath: [
    { required: true, message: '请选择分类', trigger: 'change' },
    { type: 'array', len: 2, message: '请选择到二级分类', trigger: 'change' }
  ]
});
const firstLevelCategories = ref([]);
const secondLevelCategories = ref([]);
// 计算属性：将一级和二级分类转换为级联选择器所需的格式
const cascaderOptions = computed(() => {
  
  
  const options = [];
  firstLevelCategories.value.forEach(firstLevel => {
    const children = secondLevelCategories.value
      .filter(secondLevel => secondLevel.FirstLevelCategoryId === firstLevel.Id)
      .map(secondLevel => ({
        value: secondLevel.Id,
        label: secondLevel.CategoryName || '未命名分类'
      }));
    

    options.push({
      value: firstLevel.Id,
      label: firstLevel.CategoryName || '未命名分类',
      children
    });
  });
  
  return options;
});

// 获取物料列表（带分页）
const getMaterialList = async () => {
  loading.value = true;
  try {
    // 传递分页参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    };
    const response = await materialApi.getAll(params);
    materialList.value = response.items || [];
    total.value = response.totalCount || 0;
  } catch (error) {
    ElMessage.error('获取物料列表失败');
    
  } finally {
    loading.value = false;
  }
};

// 搜索物料
const searchMaterials = async () => {
  currentPage.value = 1;
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.name
    };
    
    // 如果选择了分类，添加二级分类ID到参数中
    if (searchForm.categoryPath && searchForm.categoryPath.length === 2) {
      params.firstLevelCategoryId = searchForm.categoryPath[0];
      params.secondLevelCategoryId = searchForm.categoryPath[1];
    }
    
    const response = await searchMaterialsApi(params);
    materialList.value = response.items || [];
    total.value = response.totalCount || 0;
  } catch (error) {
    ElMessage.error('搜索物料失败');
    
  } finally {
    loading.value = false;
  }
};

// 新增物料
const addMaterial = () => {
  dialogTitle.value = '新增物料';
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields();
  }
  formData.id = 0;
  formData.status = 1;
  formData.categoryPath = [];
  dialogVisible.value = true;
};

// 编辑物料
const editMaterial = async (row) => {
  dialogTitle.value = '编辑物料';
  // 深拷贝数据
  formData.id = row.id;
  formData.materialCode = row.MaterialCode;
  formData.name = row.MaterialName;
  formData.specification = row.Specification;
  formData.description = row.Description || '';
  formData.status = row.Status || 1;
  // 设置分类路径
  if (row.SecondLevelCategory && row.SecondLevelCategory.FirstLevelCategory) {
    formData.categoryPath = [
      row.SecondLevelCategory.FirstLevelCategory.Id,
      row.SecondLevelCategory.Id
    ];
  } else {
    formData.categoryPath = [];
  }
  dialogVisible.value = true;
};

// 保存物料
    const saveMaterial = async () => {
      
      // 验证表单
      if (!formRef.value) {
        
        return;
      }
      try {
        
        await formRef.value.validate();
        

        // 准备提交数据
        const submitData = { ...formData };

        

        // 字段映射：将name映射为MaterialName
        submitData.MaterialName = submitData.name;
        

        // 处理分类数据
        if (submitData.categoryPath && submitData.categoryPath.length === 2) {
          // 确保分类ID是数字类型
          submitData.firstLevelCategoryId = parseInt(submitData.categoryPath[0], 10);
          submitData.secondLevelCategoryId = parseInt(submitData.categoryPath[1], 10);
          
        } else {
          submitData.firstLevelCategoryId = null;
          submitData.secondLevelCategoryId = null;
          
        }

        // 删除不需要提交的字段
        delete submitData.categoryPath;
        // 不需要删除name字段，因为后端可能需要

        // 检查是否有MaterialName字段
        
        
        

        if (formData.id === 0) {
          // 新增
          try {
            const response = await materialApi.add(submitData);
            
            ElMessage.success('新增物料成功');
            dialogVisible.value = false;
            getMaterialList();
          } catch (error) {
            
            
            ElMessage.error(`新增物料失败: ${error.message || '未知错误'}`);
          }
        } else {
          // 更新
          try {
            const response = await materialApi.update(formData.id, submitData);
            
            ElMessage.success('更新物料成功');
            dialogVisible.value = false;
            getMaterialList();
          } catch (error) {
            
            
            ElMessage.error(`更新物料失败: ${error.message || '未知错误'}`);
          }
        }
      } catch (error) {
        
        if (error instanceof Error) {
          ElMessage.error(error.message || '操作失败');
        } else if (typeof error === 'string') {
          // 表单验证失败的情况
          ElMessage.error('表单验证失败: ' + error);
          return;
        }
        
        ElMessage.error('保存物料失败: 请检查日志获取详细信息');
      }
};

// 删除物料
const deleteMaterial = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该物料吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await materialApi.delete(id);
    ElMessage.success('删除物料成功');
    getMaterialList();
  } catch (error) {
    if (error === 'cancel') return;
    ElMessage.error('删除物料失败');
    
  }
};

// 获取一级分类
const getFirstLevelCategories = async () => {
  try {
    const data = await materialCategoryApi.firstLevel.getAll();
    firstLevelCategories.value = data;
    // 获取所有二级分类，用于级联选择器
    await getAllSecondLevelCategories();
  } catch (error) {
    ElMessage.error('获取一级分类失败');
    
  }
};

// 获取所有二级分类
const getAllSecondLevelCategories = async () => {
  try {
    const data = await materialCategoryApi.secondLevel.getAll();
    secondLevelCategories.value = data;
    
    
    data.forEach((category, index) => {
      
      
      
      
      
    });
    
  } catch (error) {
    ElMessage.error('获取二级分类失败');
    
  }
};

// 生命周期钩子
onMounted(() => {
  getMaterialList();
  getFirstLevelCategories();
});

// 处理状态变更
const handleStatusChange = async (row) => {
  try {
    await materialApi.update(row.id, { ...row, Status: row.Status ? 1 : 0 });
    ElMessage.success('状态更新成功');
  } catch (error) {
    // 恢复状态
    row.Status = !row.Status;
    ElMessage.error('状态更新失败');
    
  }
};

// 处理分页变化
const handleCurrentChange = (current) => {
  currentPage.value = current;
  getMaterialList();
};

// 处理页面大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  getMaterialList();
};

// 处理弹窗关闭
const handleClose = () => {
  dialogVisible.value = false;
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理搜索表单中的分类变更
const handleSearchCategoryChange = (value) => {
  searchForm.categoryPath = value || [];
};

// 获取分类名称（处理可能的循环引用）
const getCategoryName = (row) => {
  if (!row || !row.SecondLevelCategory) return '';

  // 处理引用对象
  if (row.SecondLevelCategory.$ref) {
    // 尝试从二级分类列表中查找
    const category = secondLevelCategories.value.find(cat => cat.Id === parseInt(row.SecondLevelCategory.$ref));
    return category?.CategoryName || '';
  }

  return row.SecondLevelCategory.CategoryName || '';
}

// 获取一级分类名称
const getFirstLevelCategoryName = (row) => {
  if (!row || !row.SecondLevelCategory) return '';

  // 处理二级分类是引用对象的情况
  let secondLevelCategory = row.SecondLevelCategory;
  if (secondLevelCategory.$ref) {
    secondLevelCategory = secondLevelCategories.value.find(cat => cat.Id === parseInt(secondLevelCategory.$ref)) || {};
  }

  // 处理一级分类是引用对象的情况
  if (secondLevelCategory.FirstLevelCategory && secondLevelCategory.FirstLevelCategory.$ref) {
    const firstLevelCategory = firstLevelCategories.value.find(cat => cat.Id === parseInt(secondLevelCategory.FirstLevelCategory.$ref));
    return firstLevelCategory?.CategoryName || '';
  }

  return secondLevelCategory.FirstLevelCategory?.CategoryName || '';
}

// 处理表单中的分类变更
const handleFormCategoryChange = (value) => {
  formData.categoryPath = value || [];
}
</script>

<template>
  <common-layout title="物料信息管理" >
    <!-- 标题+操作按钮区 -->
    <template #header-buttons>
      <el-button type="primary" @click="addMaterial">
        <el-icon><Plus /></el-icon>
        <span>新增物料</span>
      </el-button>
    </template>

    <!-- 搜索区域 -->
    <template #search-form>
      <el-form :model="searchForm" class="search-form" :inline="true">
        <el-form-item label="物料名称" style="width: 260px;">
          <el-input v-model="searchForm.name" placeholder="请输入物料名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="物料分类" style="width: 260px;">
          <el-cascader
            v-model="searchForm.categoryPath"
            :options="cascaderOptions"
            :props="{
              value: 'value',
              label: 'label',
              children: 'children',
              expandTrigger: 'click',
              checkStrictly: false
            }"
            placeholder="请选择分类"
            @change="handleSearchCategoryChange"
            clearable
            collapse-tags
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchMaterials" style="margin-right: 10px;">
            <el-icon><Search /></el-icon>
            <span>搜索</span>
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            <span>重置</span>
          </el-button>
        </el-form-item>
      </el-form>
    </template>

    <!-- 数据区 -->
    <template #data-content>
      <el-card shadow="hover">
        <el-table v-loading="loading" :data="materialList" border style="width: 100%">
            <el-table-column prop="id" label="物料ID" width="80" />
            <el-table-column prop="MaterialCode" label="物料编码" width="120" />
            <el-table-column prop="MaterialName" label="物料名称" width="180" />
            <el-table-column label="物料分类" width="220">
                <template #default="scope">
                  {{ getCategoryName(scope.row) || '未分类' }} ({{ getFirstLevelCategoryName(scope.row) || '未分类' }})
                </template>
              </el-table-column>
            <el-table-column prop="Specification" label="规格型号" width="180" />
            <el-table-column prop="Status" label="状态" width="100">
              <template #default="scope">
                <el-switch v-model="scope.row.Status" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button size="small" type="primary" style="margin-right: 5px;" @click="editMaterial(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteMaterial(scope.row.MaterialCode)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
          </div>
        </el-card>
    </template>
  </common-layout>

    <!-- 新增/编辑物料弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :before-close="handleClose">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="formData.materialCode" placeholder="请输入物料编码" :disabled="formData.id > 0" />
        </el-form-item>
        <el-form-item label="物料名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="formData.specification" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="物料分类" prop="categoryPath">
            <el-cascader
              v-model="formData.categoryPath"
              :options="cascaderOptions"
              :props="{
                value: 'value',
                label: 'label',
                children: 'children',
                expandTrigger: 'click',
                checkStrictly: false
              }"
              placeholder="请选择分类"
              @change="handleFormCategoryChange"
              clearable
              collapse-tags
            />
        </el-form-item>
        <el-form-item label="物料描述" prop="description">
          <el-input v-model="formData.description" type="textarea" placeholder="请输入物料描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveMaterial">确定</el-button>
        </span>
      </template>
    </el-dialog>
</template>

<style scoped>
.material-info-container {
  padding: 20px;
  box-sizing: border-box;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.buttons {
  display: flex;
  gap: 10px;
}

.search-form {
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  overflow-x: auto;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 表格样式增强 */
.el-table {
  border-radius: 4px 4px 0 0;
  overflow: hidden;
}

.el-table th {
  background-color: #f7f8fa;
  font-weight: 500;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 20px;
}

.el-select {
  width: 100%;
}

.el-cascader {
  width: 100%;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer button {
  margin-left: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-form .el-input,
  .search-form .el-select {
    width: 100% !important;
    margin-left: 0 !important;
    margin-bottom: 10px;
  }

  .search-form .el-button {
    margin-left: 0 !important;
    margin-right: 10px;
  }
}
</style>